package com.ybliang.plat.common.autoconfig.webapp.interceptor;

import com.ybliang.plat.common.web.annotation.IgnoreAuthentication;
import com.ybliang.plat.common.web.annotation.IgnoreAuthorization;
import com.ybliang.plat.common.web.interceptor.AbstractPlatInterceptor;
import com.ybliang.plat.serviceapp.common.exception.BusinessException;
import com.ybliang.plat.serviceapp.common.exception.Errors;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 授权拦截器
 * @author liangyb
 *
 */
@Component
public class AuthorizationInterceptor extends AbstractPlatInterceptor {

	private static Logger LOGGER = LoggerFactory.getLogger(AuthorizationInterceptor.class);

	private static final String ACCESS_TOKEN = "AccessToken";

	private static List<String> ignoreUrlsMatchers = new ArrayList<String>();

	static{

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if(isIgnoreUrl(request)){
			return true;
		}

		if(!(handler instanceof HandlerMethod)) {
			return true;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		if(handlerMethod.getBeanType() == BasicErrorController.class) {
			return true;
		}

		Method method        = handlerMethod.getMethod();
		IgnoreAuthentication ignoreAuthentication = method.getAnnotation(IgnoreAuthentication.class);
		//无需认证、也无需验证授权
		if(null != ignoreAuthentication) {
			return true;
		}
		if(method.getDeclaringClass().isAnnotationPresent(IgnoreAuthentication.class)){
			return true;
		}
		//
        IgnoreAuthorization ignoreAuthorization = method.getAnnotation(IgnoreAuthorization.class);
		if(null != ignoreAuthorization) {
			return true;
		}
		if(method.getDeclaringClass().isAnnotationPresent(IgnoreAuthorization.class)){
			return true;
		}

		/*
        InvocationContext invocationContext = InvocationContextHolder.getInvocationContext();
        AcegiUserDetails acegiUserDetails = invocationContext.getAcegiUserDetails();
        Long              userId           = acegiUserDetails.getUserId();
        String            username          = acegiUserDetails.getUsername();
		if(StringUtils.isEmpty(username)) {
			throw new LoginException(ErrorConstants.TOKEN_IS_INVALID);
		}

		//判断是否是指定的超管
		boolean isAdminstartorUser = isAdminstartorUser(username);
		if (isAdminstartorUser) {
			return true;
		}

		//查询userId对应的Permission列表
		List<AdminResModel> permissions = adminResService.queryResByUserId(userId);
		//List<Permission> permissions = permissionService.queryPermissionsByAdminCache(uid);
		if(null == permissions || permissions.size() == 0) {
			//没有任何权限
			throw BusinessException.of(null,"你不具有该功能操作权限，请联系后台管理员");
		}

		String url = request.getRequestURI();
		boolean hasPer = permissions.stream()
				.filter(n ->n.getType()==10)
				.anyMatch(n -> url.equals(toRequestMappingUrl(n.getPermissionUrl())));
		if(hasPer) {
			//有此权限
			return true;
		}

		*/

		throw new BusinessException(Errors.SystemError.ACCESS_DENIED);
	}


	/**
	 * permissionUrl转化为RequestMapping
	 * @param permissionUrl
	 * @return
	 */
	private String toRequestMappingUrl(String permissionUrl) {
		if(StringUtils.isBlank(permissionUrl)) {
			return "";
		}
		permissionUrl = permissionUrl.trim();
		if(!permissionUrl.startsWith("/")) {
			permissionUrl = "/v1/" + permissionUrl;
		}
		return permissionUrl;
	}




	public   boolean isAdminstartorUser(String userName) {
		
		String adminstartorUsername = "openAdmin";

		if (StringUtils.isBlank(userName)) {
			return false;
		}
		if (ObjectUtils.equals(adminstartorUsername, userName)) {
			return true;
		}
		
		return false;
	}
	
	private static boolean isIgnoreUrl(HttpServletRequest request){

		return false;
	}

}
